<?php

namespace app\crontab;

//工厂任务
use app\model\User;
use app\model\UserFactory;
use app\model\UserFactorySeat;
use think\Exception;
use think\facade\Db;

class Factory
{


    /**
     * 建造工厂
     */
    public function building()
    {
        Db::startTrans();
        try {
            $user_factory_list = (new UserFactory())->where('state', FACTORY_STATE['建造中'])->select();
            foreach ($user_factory_list as $user_factory) {
                if ($user_factory->build_end_time <= date('Y-m-d H:i:s')) {
                    //建造完成
                    $user_factory->state = FACTORY_STATE['待收取'];
                    $user_factory->save();
                    //释放工人
                    $user = (new User())->find($user_factory->user_id);
                    $user->worker = $user->worker + 1;
                    $user->save();
                    var_dump('建造成功,待收取' . json_encode($user_factory));
                }
            }
            Db::commit();
           // var_dump('执行完成');

        } catch (Exception $e) {
            var_dump('执行异常' . $e->getMessage());
        }
    }


    /**
     * 生产队列
     */
    public function production()
    {
        Db::startTrans();
        try {
            $user_factory_seat_list = (new UserFactorySeat())->where('status', FACTORY_PRODUCTION['生产中'])->select();

            foreach ($user_factory_seat_list as $user_factory_seat) {
                $complete_time = strtotime($user_factory_seat->end_time);
                if ($complete_time <= time()) {
                    $user_factory_seat->status = FACTORY_PRODUCTION['待收取'];
                    $user_factory_seat->save();
                    //空余槽位+1
                    $user_factory = (new UserFactory())->find($user_factory_seat->user_factory_id);
                    $user_factory->save();


                    //自动生产下个材料
                    $user_factory_seats = (new UserFactorySeat())->where('user_id', $user_factory_seat->user_id)->where('user_factory_id', $user_factory_seat->user_factory_id)->where('status',FACTORY_PRODUCTION['队列中'])->find();

                    if ($user_factory_seats) {
                        $user_factory_seats->end_time = date('Y-m-d H:i:s',time()+$user_factory_seats->need_time);
                        $user_factory_seats->status = FACTORY_PRODUCTION['生产中'];
                        $user_factory_seats->save();
                    }

                    var_dump('生产完成,待收取' . json_encode($user_factory_seat));
                }
            }
            Db::commit();
            //var_dump('生产队列-执行完成');

        } catch (Exception $e) {
            Db::rollback();
            var_dump('生产队列-执行异常' . $e->getMessage());
        }


    }


}